import { formatPrice } from './foundation'
import storage from './storage'

export function px2rpx(px: any) {
  const rpx = (Number.parseInt(px) * 750) / systemInfo.screenWidth
  return rpx
}

/**
 * 验证是否登录如果没登录则去登录
 * @param {*} val
 * @returns
 */

export function forceLogin() {
  let userInfo = storage.getUserInfo()
  if (!userInfo || !userInfo.id) {
    // #ifdef MP-WEIXIN

    uni.navigateTo({
      url: '/pages/passport/wechatMPLogin'
    })

    // #endif

    // #ifndef MP-WEIXIN

    uni.navigateTo({
      url: '/pages/passport/login'
    })

    //  #endif
  }
}

// 需要登录才能继续的方法, 没登录跳转登录, 登录了执行回调函数
export function needLogin(callback: Function) {
  let userInfo = storage.getUserInfo()
  if (userInfo && userInfo.id) {
    callback()
  } else {
    // #ifdef MP-WEIXIN

    uni.navigateTo({
      url: '/pages/passport/wechatMPLogin'
    })

    // #endif

    // #ifndef MP-WEIXIN

    uni.navigateTo({
      url: '/pages/passport/login'
    })

    //  #endif
  }
}

/**
 * 格式化价格  1999 --> [1999,00]
 * @param {*} val
 * @returns
 */
export function goodsFormatPrice(val: any) {
  if (typeof val == 'undefined') {
    return val
  }
  let valNum = new Number(val)
  return valNum.toFixed(2).split('.')
}

export const complainStatus = {
  NEW: '新投诉',
  CANCEL: '已撤销',
  WAIT_APPEAL: '待申诉',
  // COMMUNICATION: "对话中",
  WAIT_ARBITRATION: '等待仲裁',
  COMPLETE: '已完成',
  NO_APPLY: '未申请',
  APPLYING: '申请中',
  EXPIRED: '已失效'
}
/**
 * 订单售后状态列表返回集合
 */
export const statusList = {
  APPLY: '售后申请中',
  PASS: '通过售后',
  REFUSE: '拒绝售后',
  BUYER_RETURN: '待卖家收货',
  SELLER_RE_DELIVERY: '商家换货/补发',
  SELLER_CONFIRM: '卖家确认收货',
  SELLER_TERMINATION: '卖家终止售后',
  BUYER_CONFIRM: '买家确认收货',
  BUYER_CANCEL: '买家取消售后',
  WAIT_REFUND: '等待平台退款',
  COMPLETE: '完成售后'
}

/**
 * 订单状态列表返回集合
 */
export const serviceStatus = {
  APPLY: '申请中',
  PASS: '通过售后',
  REFUSE: '拒绝售后',
  BUYER_RETURN: '买家退货，待卖家收货',
  SELLER_CONFIRM: '卖家确认收货',
  SELLER_TERMINATION: '卖家终止售后',
  BUYER_CANCEL: '买家取消售后',
  COMPLETE: '完成售后',
  WAIT_REFUND: '待平台退款'
}

/**
 * 活动状态列表返回集合
 */
export const promotionStatusWay = {
  NEW: '未开始',
  START: '已开始',
  END: '已结束',
  CLOSE: '已关闭'
}

/**
 * 订单状态列表返回集合
 */
export const orderStatusWay = {
  UNDELIVERED: '待发货',
  UNPAID: '未付款',
  PAID: '已付款',
  DELIVERED: '已发货',
  CANCELLED: '已取消',
  // COMPLETE: "已完成",
  TAKE: '待核验',
  COMPLETED: '已完成',
  STAY_PICKED_UP: '待自提'
}
/**
 * 订单类型列表返回集合
 */
export const orderTypeWay = {
  NORMAL: '普通订单',
  VIRTUAL: '虚拟订单',
  PINTUAN: '拼团订单',
  GIFT: '赠品订单',
  POINTS: '积分订单',
  KANJIA: '砍价订单'
}

/**
 * 订单促销类型列表返回集合
 * */
export const orderPromotionTypeWay = {
  NORMAL: '普通订单',
  PINTUAN: '拼团订单',
  GIFT: '赠品订单',
  VIRTUAL: '核验订单',
  KANJIA: '砍价订单',
  POINTS: '积分订单'
}

export const clientType = {
  H5: '移动端',
  PC: 'PC端',
  WECHAT_MP: '小程序端',
  APP: 'APP端'
}

/**
 * 订单类型列表返回集合
 */
export const orderType = [
  { label: '普通订单', value: 'NORMAL' },
  { label: '虚拟订单', value: 'VIRTUAL' },
  { label: '采购订单', value: 'PURCHASE' },
  { label: '赠品订单', value: 'GIFT' }
]

/**
 * 是否获取触底刷新
 */
export function enableFetchReachBottom(total: number, pageNumber: number, pageSize: number) {
  return total > pageNumber * pageSize
}

/**
 * 金钱单位置换  2999 --> 2,999.00
 * @param val
 * @param unit
 * @param location
 * @returns {*}
 */
export function unitPrice(val: number, unit?: string, location?: string) {
  if (!val) val = 0
  const price = formatPrice(val)
  if (location === 'before') return price.substr(0, price.length - 3)

  if (location === 'after') return price.substr(-2)

  return (unit || '') + price
}

/**
 * 脱敏姓名
 */

export function noPassByName(str: string) {
  if (str) {
    if (str.length <= 3) return `*${str.substring(1, str.length)}`
    else if (str.length > 3 && str.length <= 6) return `**${str.substring(2, str.length)}`
    else if (str.length > 6) return `${str.substring(0, 2)}****${str.substring(6, str.length)}`
  } else {
    return ''
  }
}

/**
 * 处理unix时间戳，转换为可阅读时间格式
 * @param unix
 * @param format
 * @returns {*|string}
 */
export function unixToDate(unix: number, format: string) {
  let _format = format || 'yyyy-MM-dd hh:mm:ss'
  const d = new Date(unix * 1000)
  const o = {
    'M+': d.getMonth() + 1,
    'd+': d.getDate(),
    'h+': d.getHours(),
    'm+': d.getMinutes(),
    's+': d.getSeconds(),
    'q+': Math.floor((d.getMonth() + 3) / 3),
    S: d.getMilliseconds()
  }
  if (/(y+)/.test(_format)) {
    _format = _format.replace(RegExp.$1, `${d.getFullYear()}`.substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(_format)) {
      _format = _format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length))
    }
  }
  return _format
}

/**
 * 13888888888 -> 138****8888
 * @param mobile
 * @returns {*}
 */
export function secrecyMobile(mobile: string) {
  mobile = String(mobile)
  if (!/\d{11}/.test(mobile)) return mobile

  return mobile.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}

/**
 * 清除逗号
 *
 */
export function clearStrComma(str: string) {
  str = str.replace(/,/g, '') // 取消字符串中出现的所有逗号
  return str
}

/**
 * 判断用户是否登录
 * @param val  如果为auth则判断是否登录
 * 如果传入 auth 则为判断是否登录
 */
export function isLogin(val: string) {
  const userInfo = storage.getUserInfo()
  if (val === 'auth') return userInfo && !!userInfo.id
  else return storage.getUserInfo()
}

/**
 * 获取当前加载的页面对象
 * @param val
 */
export function getPages(val: string) {
  const pages = getCurrentPages() // 获取加载的页面
  const currentPage = pages[pages.length - 1] // 获取当前页面的对象
  const url = currentPage.route // 当前页面url

  return val ? currentPage : url
}

/**
 * 服务状态列表
 */
export function serviceStatusList(val: keyof typeof serviceStatus) {
  return serviceStatus[val]
}

/**
 * 订单状态列表
 */
export function orderStatusList(val: keyof typeof orderStatusWay) {
  return orderStatusWay[val]
}

/**
 * 订单状态列表
 */
export function getOrderStatusValue(val: keyof typeof orderStatusWay) {
  return orderStatusWay[val]
}

/**
 * 订单类型列表
 */
export function orderTypeList(val: keyof typeof orderTypeWay) {
  return orderTypeWay[val]
}

/**
 * 订单促销类型
 * */
export function orderPromotionTypeList(val: keyof typeof orderPromotionTypeWay) {
  return orderPromotionTypeWay[val]
}

/**
 * 订单状态列表
 */
export function orderClientType(val: keyof typeof clientType) {
  return clientType[val]
}

/**
 * 投诉列表
 * @returns
 */
export function complainStatusList(val: keyof typeof complainStatus) {
  return complainStatus[val]
}

/**
 * 活动状态活动状态
 * @returns
 */
export function promotionStatus(val: keyof typeof promotionStatusWay) {
  return promotionStatusWay[val]
}

// 去重
export function uniqueFunc(arr: [], uniId: string) {
  const res = new Map()
  // arr.forEach((item) => console.log(!res.has(item[uniId]) , res.set(item[uniId], 1)));
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1))
}

/**
 * 跳转到登录页面
 */
export function navigateToLogin() {
  // #ifndef MP-WEIXIN
  uni.navigateTo({
    url: '/pages/passport/login'
  })
  //  #endif
  // #ifdef MP-WEIXIN
  uni.navigateTo({
    url: '/pages/passport/wechatMPLogin'
  })
  // #endif
}

/**
 * 人性化显示时间
 *
 * @param {Object} datetime
 */
export function beautifyTime(datetime = '') {
  if (datetime == null || !datetime) return ''

  datetime = timestampToTime(datetime).replace(/-/g, '/')

  const time = new Date()
  let outTime = new Date(datetime)
  if (/^[1-9]\d*$/.test(datetime)) outTime = new Date(Number.parseInt(datetime) * 1000)

  if (time.getTime() < outTime.getTime()) return parseTime(outTime, '{y}/{m}/{d}')

  if (time.getFullYear() !== outTime.getFullYear()) return parseTime(outTime, '{y}/{m}/{d}')

  if (time.getMonth() !== outTime.getMonth()) return parseTime(outTime, '{m}/{d}')

  if (time.getDate() !== outTime.getDate()) {
    const day = outTime.getDate() - time.getDate()
    if (day === -1) return parseTime(outTime, '昨天 {h}:{i}')

    if (day === -2) return parseTime(outTime, '前天 {h}:{i}')

    return parseTime(outTime, '{m}-{d}')
  }

  if (time.getHours() !== outTime.getHours()) return parseTime(outTime, '{h}:{i}')

  let minutes = outTime.getMinutes() - time.getMinutes()
  if (minutes === 0) return '刚刚'

  minutes = Math.abs(minutes)
  return `${minutes}分钟前`
}
// 时间转换
function timestampToTime(timestamp: number) {
  const date = new Date(timestamp) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const Y = `${date.getFullYear()}-`
  const M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}-`
  const D = `${date.getDate()} `
  const h = `${date.getHours()}:`
  const m = `${date.getMinutes()}:`
  const s = date.getSeconds()
  return Y + M + D + h + m + s
}

/**
 * 时间格式化方法
 *
 * @param {(Object|string|number)} time
 * @param {String} cFormat
 * @returns {String | null}
 */
export function parseTime(time: any, cFormat: string) {
  if (arguments.length === 0) return null

  let date
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'

  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) time = Number.parseInt(time)

    if (typeof time === 'number' && time.toString().length === 10) time = time * 1000

    date = new Date(time.replace(/-/g, '/'))
  }

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }

  return format.replace(/{([ymdhisa])+}/g, (result, key: keyof typeof formatObj) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][value]

    return value.toString().padStart(2, '0')
  })
}
/**
 * 订单售后状态
 */
export function orderAftersaleStatusList(val: keyof typeof statusList) {
  return statusList[val]
}

export function eachReplaceKey(data: []) {
  const item = Array<any>()
  data.forEach((list: any) => {
    const newData = Object()
    newData.text = list.name || list.labelName
    newData.value = list.id || list.logisticsId
    if (list.children && list.children.length > 0) newData.children = eachReplaceKey(list.children)

    item.push(newData)
  })
  return item
}

export function orderDataProcess(orderData: any[]) {
  orderData.forEach((element: any) => {
    const specs = element?.groupSpecs?.split('},{') || element?.specs?.split('},{')
    if (specs) {
      const specsResult: any = []
      specs.forEach((item: any, index: number) => {
        let specsStr
        if (specs.length > 1) {
          if (index === 0) specsStr = `${item}}`
          else if (index === specs.length - 1) specsStr = `{${item}`
          else specsStr = `{${item}}`
        } else {
          specsStr = item
        }

        try {
          const specsJson = JSON.parse(specsStr)
          delete specsJson.images
          specsResult.push(specsJson)
        } catch (e) {}
      })
      let groupSpecsStr = ''
      specsResult.forEach((item: any) => {
        groupSpecsStr += `${Object.values(item)} `
      })
      element.groupSpecsStr = groupSpecsStr
    }
    element.imageList = element?.groupImages?.split(',')
  })
}
